<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex" value="">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj, index) in arr" :key="obj.id">
          <td>{{ index + 1 }}</td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="ptn(index)">删除</button>
            <button @click="atn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "",
      age: 0,
      sex: "男",
      nul: null,
      arr: [],
    };
  },
  methods: {
    btn() {
      if (this.name.length == 0 || this.age.length == 0) {
        alert("不能为空");
        return;
      }
      let newarr = {
        name: this.name,
        age: this.age,
        sex: this.sex,
      };
      if (this.nul !== null) {
        this.$set(this.arr, this.nul, newarr);
        this.nul = null;
      } else {
        this.arr.push(newarr);
      }
    },
    ptn(and) {
      this.arr.splice(and, 1);
    },
    atn(index) {
      let nb = this.arr[index];
      this.name = nb.name;
      this.age = nb.age;
      this.sex = nb.sex;
      this.nul = index;
    },
  },
};
</script>
